#-*- encoding: utf-8 -*-

"""
新浪实时行情接口
该接口用于从新浪获取实时行情数据

http://hq.sinajs.cn/?_=1333681844792&list=

var hq_str_sh600028="中国石化,7.21,7.20,7.17,7.21,7.14,7.17,7.18,15407286,110416294,378941,7.17,690301,7.16,2035251,7.15,1030200,7.14,678000,7.13,16100,7.18,216173,7.19,1963000,7.20,272882,7.21,112200,7.22,2012-04-06,11:06:32";

"""

import urllib.request
import urllib.response
import urllib.error
import re
import data.QuoteData

SINA_QUOTE_URL = "http://hq.sinajs.cn/"
SINA_KEY_IDS = "list"

SINA_QUOTE_VALUES = [\
    ("名称", "Name"),\
    ("今开", "Open"),\
    ("昨收", "Previous"),\
    ("当前", "Price"),\
    ("最高", "High"),\
    ("最低", "Low"),\
    ("买一", "Buy"),\
    ("卖一", "Sell"),\
    ("成交量", "Volume"),\
    ("成交额", "Capital"),\
    ("买一量", "BuyVolume1"),\
    ("买一", "Buy1"),\
    ("买二量", "BuyVolume2"),\
    ("买二", "Buy2"),\
    ("买三量", "BuyVolume3"),\
    ("买三", "Buy3"),\
    ("买四量", "BuyVolume4"),\
    ("买四", "Buy4"),\
    ("买五量", "BuyVolume5"),\
    ("买五", "Buy5"),\
    ("卖一量", "SellVolume1"),\
    ("卖一", "Sell1"),\
    ("卖二量", "SellVolume2"),\
    ("卖二", "Sell2"),\
    ("卖三量", "SellVolume3"),\
    ("卖三", "Sell3"),\
    ("卖四量", "SellVolume4"),\
    ("卖四", "Sell4"),\
    ("卖五量", "SellVolume5"),\
    ("卖五", "Sell5"),\
    ("日期", "Date"),\
    ("时间", "Time"),\
    ]

def checkSinaStockCode(code):
    #print("check stock code:", code)
    if code==None or code=="":
        return
    if len(code)!=6:
        return code
    if code.startswith("sh") or code.startswith("sz"):
        return code

    pss = re.compile("^(600|601|900)\d{3}$")
    m = pss.match(code)
    #print("check ss", m)
    if m!=None:
        return "sh"+code
    
    psz = re.compile("^(000|002|300)\d{3}$")
    m = psz.match(code)
    #print("check sz", m)
    if m!=None:
        return "sz"+code

    return code

def createSinaIds(ids):
    """ ids maybe string or list, create url paramter ids from it """
    ret = ""
    if type(ids) is str:
        #print("is str")
        if ids!=None and ids!="":
            vals = ids.split(",")
            for id in vals:
                if id==None or id=="":
                    continue
                if len(ret)>0:
                    ret = ret+","
                ret = ret + checkSinaStockCode(id.strip())
    elif type(ids) is list:
        #print("is list")
        for id in ids:
            if id==None and id=="":
                continue
            if len(ret)>0:
                ret = ret+","
            ret = ret + checkSinaStockCode(id.strip())
            #print(ret)
    else:
        #print("...", type(ids))
        pass

    return ret

def parseSinaQuoteData(line):
    """ 读取新浪实时数据接口返回的信息，并转换为需要的数据格式 """
    if line==None or line=="" or line.strip()=="":
        return None

    startIndex = line.find('"')
    if startIndex<0:
        startIndex = -1

    endIndex = line.rfind('"')
    if endIndex<0:
        endIndex = len(line)

    line = line[startIndex+1:endIndex]
    values = line.split(",", len(SINA_QUOTE_VALUES)-1)

    index = 0
    quote = []
    for k1, k2 in SINA_QUOTE_VALUES:
        print(k1, values[index])
        quote.append((k2, values[index]))
        
        index += 1

    return quote
    

def sinaQuote(ids):
    if ids==None or ids=="":
        return None

    params = {SINA_KEY_IDS: createSinaIds(ids)}
    quoteUrl = SINA_QUOTE_URL+"?"+SINA_KEY_IDS+"="+createSinaIds(ids) #urllib.parse.urlencode(params)

    print(quoteUrl)

    try:
        f = urllib.request.urlopen(quoteUrl)

        line = f.readline()
        quotes = []
        while len(line)>0:
            line = str(line, "gbk")
            #print(line)
            quotes.append(parseSinaQuoteData(line))

            line = f.readline()

        print(quotes)
        qds = []
        for q in quotes:
            qd = data.QuoteData.RTQuote()
            qd.fromSinaQuote(q)
            qds.append(qd)
        print(qds)
    except urllib.error.URLError as ue:
        print("Error: ", ue)
